//
//  PictureSelectViewController.swift
//  新浪微博
//
//  Created by 李赛 on 15/5/25.
//  Copyright (c) 2015年 李赛. All rights reserved.
//

import UIKit

class PictureSelectViewController: UICollectionViewController {

    // 图像数组
    var pictureList = [UIImage]()
    
    override func viewDidLoad() {
        super.viewDidLoad()

        // 注册通知
        regNotification()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    private func regNotification() {
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "selectPicture:", name: PictureSelectorNotification, object: nil)
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "removePicture:", name: PictureRemoveNotification, object: nil)
    }
    
    
    deinit {
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    
    
    // 选择照片
    func selectPicture(notification : NSNotification) {
        // 取出通知中得cell 
        let cell = notification.object as! PictureSelectCell
        if cell.image != nil {
            println("已经设置图片了")
            return
        }
        
        // 需要用户的授权
        /**
            case PhotoLibrary       相册，使用 iPhoto，iTunes 同步的照片，不能删除，包含保存的照片
            默认的类别
            case Camera             相机
            case SavedPhotosAlbum   保存的照片，从软件保存，或者相机拍摄，能够删除
        */
        if !UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.PhotoLibrary) {
            println("不支持访问相册")
            return
        }
        
        // 选择照片  实例化选择器 然后modal
        let picker = UIImagePickerController()
        // 设置代理 通过代理方法  获取照片
        picker.delegate = self
        
        // 指定类型
        picker.sourceType = UIImagePickerControllerSourceType.SavedPhotosAlbum
        
        // 指定用户是否编辑  在用户选择头像时可以设置
        /**
        picker.allowsEditing = true
        */
        presentViewController(picker, animated: true, completion: nil)
    }
    
    func removePicture(notification : NSNotification){
        // 将照片从数组中移除 并且刷新
        let cell = notification.object as! PictureSelectCell
        
        // 根据cell计算索引
        if let indexPath = collectionView?.indexPathForCell(cell) {
            pictureList.removeAtIndex(indexPath.item)
            
            // 刷新
            collectionView?.reloadData()
        }
        
    }
    
    // MARK: UICollectionViewDataSource
    override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        return pictureList.count + 1
    }

    override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier("PictureSelectorCell", forIndexPath: indexPath) as! PictureSelectCell
    
        // 判断 indexPath.item 是否超出范围  最后一项显示按钮
        if indexPath.item < pictureList.count {
            cell.image = pictureList[indexPath.item]
        } else {
            cell.image = nil
        }
    
        return cell
    }

}

extension PictureSelectViewController : UIImagePickerControllerDelegate, UINavigationControllerDelegate {
    
    func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage!, editingInfo: [NSObject : AnyObject]!) {
        // 将用户选择的照片添加到数组
        pictureList.append(image.scaleImage(320))
        // 重新加载数据
        collectionView?.reloadData()
        
        // 关闭控制器
        dismissViewControllerAnimated(true, completion: nil)
        
    }
    
}

